package com.nameli.SIM.util;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.io.InputStreamReader;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Properties;

/**
 * @author NAME-L
 * @Description 读取配置文件工具类
 * 对于自定义配置文件可以通过此方法获取配置文件中的属性值
 * 对于 application.properties/yml 核心配置文件，可以通过 @Value("${ key }")获取属性值
 * @className PropertiesUtil
 * @date 2021-12-01 14:23:09
 */
public class PropertiesUtil {

    private static final Log log = LogFactory.getLog(PropertiesUtil.class);
    private static final String REPOSITORY_PROPERTIES = "/system.properties";//核心配置文件
    private static final Map<String , Properties> PROPERTIE_MAP = new HashMap();


    static {
        Properties properties = init(REPOSITORY_PROPERTIES);
        Iterator it = properties.keySet().iterator();
        while (it.hasNext()){
            String name = (String)it.next();
            String file = properties.getProperty(name);
            Properties p = init("/" + file);
            PROPERTIE_MAP.put(name, p);
        }
    }

    private static Properties init(String path) {
        Properties properties = new Properties();
        try {
            log.info("Enter configuration file loading!");
            properties.load(PropertiesUtil.class.getResourceAsStream(path));
            log.info("End of profile loading! ");
        } catch (Exception e) {
            e.printStackTrace();
            log.error("配置文件读取异常", e);
        }
        return properties;
    }
    /**
     * 根据配置文件中的key获取value
     * @param key
     * @return
     */
    public static String getProperty(String pathName , String key) {
        Properties properties = PROPERTIE_MAP.get(pathName);
        String value = properties.getProperty(key.trim());
        if (EmptyUtil.isEmpty(value)) {
            return null;
        }
        return value.trim();
    }


}
